package edu.office.applicationRepository;

import edu.office.entities.Major;
import edu.office.entities.TeacherAdmin;
import edu.office.entities.Teachermajor;
import edu.office.tools.EOMessage;
import edu.office.tools.EOMessage1;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Named("teachermajorRepositoryA")
@ApplicationScoped
public class TeachermajorRepository extends ApplicationCommonRepository<Teachermajor>{

    @Inject
    MajorRepository majorRepository;
    @Inject
    TeacherAdminRepository teacherAdminRepository;


    public Set<Major> getTeachMajors(TeacherAdmin teacherAdmin) {
         Set<Major> teachMajors = new HashSet<>();
            List<Teachermajor> ts = find("teacherid",teacherAdmin.getID()).list();
            ts.forEach((teachermajor) -> teachMajors.add(majorRepository.find("ID",teachermajor.getMAJORID()).firstResult()));

        return teachMajors;
    }


    public String mycreate(Teachermajor teachermajor) {
        if(list("select * from teachermajor where MAJORID=?1 and TEACHERID=?2"
                ,teachermajor.getMAJORID(),teachermajor.getTEACHERID()
        ).isEmpty()){
            create(teachermajor); return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
        } else {
            return EOMessage.getEOMessageENUM(EOMessage1.Already_Exist);
        }
    }

    public void completeMajorSelection(TeacherAdmin teacherAdmin, Set<Major> existedMajors_A, Set<Major> selectedMajors_B) {
        //根据教师确定专业，如果需要增加功能：根据专业确定教师的话，则可以参考这部分
        //获得要删除的
        Set<Major> removedMajors = new HashSet<>();
        removedMajors.addAll(existedMajors_A);
        removedMajors.removeAll(selectedMajors_B);
        //执行删除
        removedMajors.forEach((major) -> {
            delete("delete from teachermajor where teacherid=" + teacherAdmin.getID()
                    + " and majorid=" + major.getID());
        });
        //获得要增加的
        selectedMajors_B.removeAll(existedMajors_A);
        selectedMajors_B.forEach((Major major) -> {
            Teachermajor teachermajorajor = new Teachermajor();
            teachermajorajor.setTEACHERID(teacherAdmin.getID());
            teachermajorajor.setMAJORID(major.getID());
            create(teachermajorajor);
        });
    }


    public String getMajorsString(TeacherAdmin teacherAdmin) {
        String majorsString = "";
        List<Teachermajor> ts =list("TEACHERID",teacherAdmin.getID());
        for(Teachermajor teachermajor:ts)
            majorsString += "," + teachermajor.getMAJORID();
        if (majorsString.length() > 1) {
            majorsString = majorsString.substring(1);
        }
        return majorsString;

    }
}
